<template>
  <div style="margin-top: 50px">
    <el-form :model="value" ref="productAttrForm" label-width="140px" class="form-inner-container" size="small">
      <el-form-item label="商品分类" prop="catId">
        <treeselect v-model="value.catId" :options="menuOptions" :normalizer="normalizer" :show-count="true"
                    @select="getGoodsAttrCateList"
                    placeholder="选择商品分类"/>
      </el-form-item>
      <el-form-item label="是否开启属性配置：" prop="isSku">
        <el-radio-group v-model="value.isSku">
          <el-radio v-for="dict in SHOW" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <!--      <el-form-item label="属性配置：">
              <el-card shadow="never" class="cardBg">
                <div v-for="(goodsAttr,idx) in selectGoodsAttr">
                  <el-checkbox-group>
                    <el-checkbox v-for="item in selectGoodsAttr[idx].valueList" :label="item.name" :key="item.name"
                                 class="littleMarginLeft"></el-checkbox>
                  </el-checkbox-group>
                  自定义属性值: <el-input v-model="item"></el-input>
                </div>
              </el-card>
            </el-form-item>-->
      <el-form-item label="商品规格：">
        <el-card shadow="never" class="cardBg">
          <div v-for="(goodsAttr,idx) in selectGoodsAttr">
            {{ goodsAttr.goodsAttributeName }}：
            <el-checkbox-group v-model="goodsAttrChecked" @change="checkBoxChange($event,idx)">
            <span v-for="(item0,index) in goodsAttr.valueList">
              <el-checkbox :label="item0.name" :key="item0.goodsAttributeValueId"
                           class="littleMarginLeft"></el-checkbox>
                <el-button type="text" v-if="item0.isAdd" class="littleMarginLeft"
                           @click="handleRemoveGoodsAttrValue(idx,index)">删除
                </el-button>
              </span>
            </el-checkbox-group>
            <div>
              <!--              <el-checkbox-group>
                              <div v-for="(item,index) in selectGoodsAttr[idx].valueList" style="display: inline-block"
                                   class="littleMarginLeft">
                                <el-checkbox :label="item.name" :key="item.goodsAttributeValueId"></el-checkbox>
                                <el-button type="text" class="littleMarginLeft" @click="handleRemoveGoodsAttrValue(idx,index)">删除
                                </el-button>
                              </div>
                            </el-checkbox-group>-->
              <el-input  v-model="selectGoodsAttr[idx].addGoodsAttrValue" style="width: 160px;margin-left: 10px" clearable></el-input>
              <el-button class="littleMarginLeft" @click="handleAddGoodsAttrValue(idx)">增加</el-button>
            </div>
          </div>
        </el-card>
        <el-table style="width: 100%;margin-top: 20px"
                  :data="value.skuStockList"
                  border>
          <el-table-column
            v-for="(item,index) in selectGoodsAttr"
            :label="item.goodsAttributeName"
            :key="item.goodsAttributeId"
            align="center">
            <template v-slot="scope">
              {{ getGoodsSkuSp(scope.row, index) }}
            </template>
          </el-table-column>
          <el-table-column
            label="销售价格"
            width="100"
            align="center">
            <template v-slot="scope">
              <el-input v-model="scope.row.price"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="寄售价格"
            width="100"
            align="center">
            <template v-slot="scope">
              <el-input v-model="scope.row.jsPrice"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="商品库存"
            width="80"
            align="center">
            <template v-slot="scope">
              <el-input v-model="scope.row.inventory"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="80"
            align="center">
            <template v-slot="scope">
              <el-button
                type="text"
                @click="handleRemoveGoodsSku(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          style="margin-top: 20px"
          @click="handleRefreshGoodsSkuList">刷新列表
        </el-button>
        <!--        <el-button
                  type="primary"
                  style="margin-top: 20px"
                  @click="handleSyncProductSkuPrice">同步价格
                </el-button>
                <el-button
                  type="primary"
                  style="margin-top: 20px"
                  @click="handleSyncProductSkuStock">同步库存
                </el-button>-->
      </el-form-item>
      <el-form-item style="text-align: center">
        <el-button size="medium" @click="handlePrev">上一步，填写商品促销</el-button>
        <el-button type="primary" size="medium" @click="handleAudit">审核</el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="审核商品"
               :visible.sync="auditDialogVisible"
               width="40%">
      <el-form :model="auditForm"
               ref="auditForm"
               label-width="150px">
        <el-form-item label="审核意见：">
          <el-input type="textarea" v-model="auditForm.opinion" style="width: 200px"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button type="danger" @click="handleSubmitAudit(false)">拒 绝</el-button>
      <el-button type="success" @click="handleSubmitAudit(true)">通 过</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {DICT_TYPE, getDictDatas} from "@/utils/dict";
import {getGoodsAttributeList,getGoodsCatList,audit} from "@/api/supplier/goodsAudit";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";


export default {
  name: "GoodsAttrDetail",
  components: {Treeselect},
  props: {
    value: Object,
    isAudit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      SHOW: getDictDatas(DICT_TYPE.JKY_IS_SHOW),
      selectGoodsAttr: [],
      addGoodsAttrValue: '',
      menuOptions: [],
      goodsAttrChecked: [],
      goodsAttrCheckedArr: [],
      auditDialogVisible:false,
      auditForm: {
        opinion: undefined
      }
    }
  },
  computed: {
    //商品的编号
    goodsId() {
      return this.value.goodsId;
    },
    catId() {
      return this.value.catId;
    },
    skuStockList() {
      return this.value.skuStockList;
    },
  },
  created() {
    this.getTreeselect()
    this.getGoodsAttrCateList(this.value)
  },
  watch: {
    goodsId: function (newValue) {
      if (this.hasEditCreated) return;
      if (newValue === undefined || newValue == null || newValue === 0) return;
      this.handleEditCreated();
    },
    catId(value) {
      this.getGoodsAttrCateList(this.value)
    },
    skuStockList(value) {
      console.log('skuStockListvalue', value)
    },
  },
  methods: {
    handleSubmitAudit(isAdopt) {
      audit({goodsId: this.goodsId,opinion: this.auditForm.opinion,passedOrNot: isAdopt}).then(res => {
        this.$message.success(isAdopt?'审核已通过':'审核已拒绝')
        this.auditDialogVisible = false
        this.$router.go(-1)
      })
    },
    checkBoxChange(checked,idx) {
      this.goodsAttrCheckedArr[idx] = []
      let attrId = this.selectGoodsAttr[idx].goodsAttributeId
      let key = this.selectGoodsAttr[idx].goodsAttributeName
      for (let checkedElement of checked) {
        for (let value of this.selectGoodsAttr[idx].valueList) {
          if (checkedElement === value.name) {
            this.goodsAttrCheckedArr[idx].push({'attributeId':attrId,'key':key,'value':checkedElement})
          }
        }
      }
    },
    handleRemoveGoodsSku(index, row) {
      let list = this.value.skuStockList;
      if (list.length === 1) {
        list.pop();
      } else {
        list.splice(index, 1);
      }
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.catId,
        label: node.catName,
        children: node.children
      };
    },
    getTreeselect() {
      getGoodsCatList().then(response => {
        console.log('response=======', response)
        this.menuOptions = this.handleTree(response.data, "catId");
      });
    },
    handleRefreshGoodsSkuList() {
      this.$confirm('刷新列表将导致sku信息重新生成，是否要刷新', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.refreshGoodsSkuList();
      });
    },
    getGoodsSkuSp(row, index) {
      let spData = JSON.parse(row.spData);
      console.log('spData==',spData)
      if (spData != null && index < spData.length) {
        return spData[index].value;
      } else {
        return null;
      }
    },
    refreshGoodsSkuList() {
      this.value.skuStockList = [];
      // let skuList = this.value.skuStockList;
      //只有一个属性时
      console.log('this.goodsAttrChecked===', this.goodsAttrCheckedArr)

      if (this.goodsAttrCheckedArr.length === 1) {
        let attr = this.goodsAttrCheckedArr[0];
        for (let i = 0; i < attr.length; i++) {
          this.value.skuStockList.push({
            spData: JSON.stringify([{attribute_id:attr[i].attributeId,key: attr[i].key, value: attr[i].value}])
          });
        }
      } else if (this.goodsAttrCheckedArr.length === 2) {
        let attr0 = this.goodsAttrCheckedArr[0];
        let attr1 = this.goodsAttrCheckedArr[1];
        for (let i = 0; i < attr0.length; i++) {
          if (attr1.length === 0) {
            this.value.skuStockList.push({
              spData: JSON.stringify([{attribute_id:attr0[i].attributeId,key: attr0[i].key, value: attr0[i].value}])
            });
            continue;
          }
          for (let j = 0; j < attr1.length; j++) {
            let spData = [];
            spData.push({attribute_id:attr0[i].attributeId,key: attr0[i].key, value: attr0[i].value});
            spData.push({attribute_id:attr1[j].attributeId,key: attr1[j].key, value: attr1[j].value});
            this.value.skuStockList.push({
              spData: JSON.stringify(spData)
            });
          }
        }
      } else {
        let attr0 = this.goodsAttrCheckedArr[0];
        let attr1 = this.goodsAttrCheckedArr[1];
        let attr2 = this.goodsAttrCheckedArr[2];
        for (let i = 0; i < attr0.length; i++) {
          if (attr1.length === 0) {
            this.value.skuStockList.push({
              spData: JSON.stringify([{attribute_id:attr0[i].attributeId,key: attr0[i].key, value: attr0[i].value}])
            });
            continue;
          }
          for (let j = 0; j < attr1.length; j++) {
            if (attr2.length === 0) {
              let spData = [];
              spData.push({attribute_id:attr0[i].attributeId,key: attr0.key, value: attr0.value});
              spData.push({attribute_id:attr1[j].attributeId,key: attr1.key, value: attr1.value});
              this.value.skuStockList.push({
                spData: JSON.stringify(spData)
              });
              continue;
            }
            for (let k = 0; k < attr2.length; k++) {
              let spData = [];
              spData.push({attribute_id:attr0[i].attributeId,key: attr0[i].key, value: attr0[i].value});
              spData.push({attribute_id:attr1[j].attributeId,key: attr1[j].key, value: attr1[j].value});
              spData.push({attribute_id:attr2[k].attributeId,key: attr2[k].key, value: attr2[k].value});
              this.value.skuStockList.push({
                spData: JSON.stringify(spData)
              });
            }
          }
        }
      }
    },
    handleAddGoodsAttrValue(idx) {
      let valueList = this.selectGoodsAttr[idx].valueList;
      if (this.selectGoodsAttr[idx].addGoodsAttrValue == null || this.selectGoodsAttr[idx].addGoodsAttrValue === '') {
        this.$message({
          message: '属性值不能为空',
          type: 'warning',
          duration: 1000
        });
        return
      }
      if (valueList.map(item => item.name).indexOf(this.selectGoodsAttr[idx].addGoodsAttrValue) !== -1) {
        this.$message({
          message: '属性值不能重复',
          type: 'warning',
          duration: 1000
        });
        return;
      }
      this.selectGoodsAttr[idx].valueList.push({
        name: this.selectGoodsAttr[idx].addGoodsAttrValue,
        goodsAttributeValueId: this.selectGoodsAttr[idx].addGoodsAttrValue,
        isAdd: true
      });
      this.selectGoodsAttr[idx].addGoodsAttrValue = null;
    },
    handleRemoveGoodsAttrValue(idx, index) {
      this.goodsAttrCheckedArr[idx] = this.goodsAttrCheckedArr[idx].filter(item => item.value !== this.selectGoodsAttr[idx].valueList[index].name)
      this.selectGoodsAttr[idx].valueList.splice(index, 1);
    },
    handleEditCreated() {
      //根据商品属性分类id获取属性和参数
    },
    change(value) {
      console.log('change======', value)
    },
    getGoodsAttrCateList(value) {
      if (value.catId) {
        getGoodsAttributeList({id: value.catId}).then(res => {
          this.selectGoodsAttr = res.data
        });
      }
    },
    getProductAttrList(type, cid) {
    },
    //获取设置的可手动添加属性值
    getEditAttrOptions(id) {
    },
    handlePrev() {
      this.$emit('prevStep')
    },
    handleNext() {
      this.$emit('nextStep')
    },
    handleAudit() {
      this.auditDialogVisible = true
    },
  }
}
</script>

<style scoped>
.littleMarginLeft {
  margin-left: 10px;
}

.littleMarginTop {
  margin-top: 10px;
}

.paramInput {
  width: 250px;
}

.paramInputLabel {
  display: inline-block;
  width: 100px;
  text-align: right;
  padding-right: 10px
}

.cardBg {
  background: #F8F9FC;
}
</style>
